from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QColor
from qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBase

from tools import PPtReplace
from PySide6.QtWidgets import QFrame, QVBoxLayout, QAbstractItemView, QApplication, QHBoxLayout
from qfluentwidgets import LineEdit, LineEditButton, FluentIcon, PushButton, StateToolTip, InfoBar, ComboBox, \
    TransparentToolButton, TitleLabel, isDarkTheme
from components import OpenFileDialog, TableFrame
from pandas import read_excel
from common import PPtReplaceThread
from view.base import ReturnView


class HelpDialog(MaskDialogBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        c = 0 if isDarkTheme() else 255
        self.setMaskColor(QColor(c, c, c, 200))

        self.vBox = QVBoxLayout(self.widget)
        self.vBox.setContentsMargins(0, 0, 0, 0)
        self.vBox.setSpacing(0)

        self.closeButton = TransparentToolButton(FluentIcon.CLOSE, self.widget)
        self.closeButton.clicked.connect(self.close)

        self.title = TitleLabel('请参考 Word数据替换帮助', self.widget)

        self.vBox.addWidget(self.closeButton, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
        self.vBox.addWidget(self.title, 0, Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter)


class PPtReplaceView(ReturnView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.helpButton = TransparentToolButton(FluentIcon.HELP, self)
        self.helpButton.setFixedSize(40, 40)
        self.helpButton.clicked.connect(self.on_helpButton_clicked)

        self.title = TitleLabel('PPT数据替换', self)

        self.templatePath = LineEdit()
        self.templatePath.setFixedHeight(30)
        self.templatePath.setPlaceholderText('请选择模板文件...')
        self.templatePath.setClearButtonEnabled(True)
        self.openFileButton = LineEditButton(FluentIcon.FOLDER, self.templatePath)
        self.templatePath.hBoxLayout.addWidget(self.openFileButton)
        self.openFileButton.clicked.connect(self.get_template_path)

        self.startButton = PushButton()
        self.startButton.setText('开始')
        self.startButton.clicked.connect(self.startButtonEvent)

        self.excelEdit = LineEdit()
        self.excelEdit.setFixedHeight(30)
        self.excelEdit.setPlaceholderText('请选择Excel数据文件...')
        self.excelEdit.setClearButtonEnabled(True)
        self.openExcelButton = LineEditButton(FluentIcon.FOLDER, self.templatePath)
        self.excelEdit.hBoxLayout.addWidget(self.openExcelButton)
        self.openExcelButton.clicked.connect(self.get_excel_path)

        self.saveEdit = LineEdit()
        self.saveEdit.setFixedHeight(30)
        self.saveEdit.setPlaceholderText('请选择PPT文件保存路径...')
        self.saveEdit.setClearButtonEnabled(True)
        self.saveDirButton = LineEditButton(FluentIcon.FOLDER, self.templatePath)
        self.saveEdit.hBoxLayout.addWidget(self.saveDirButton)
        self.saveDirButton.clicked.connect(self.get_save_dir)

        self.table = TableFrame()
        self.table.setHeaders(['键', '值'])
        self.table.tableView.setEditTriggers(QAbstractItemView.EditTrigger.CurrentChanged)

        self.hBox.addWidget(self.helpButton, 0, Qt.AlignmentFlag.AlignRight)
        self.vBox.addLayout(self.hBox)
        self.vBox.addWidget(self.title, 0, Qt.AlignmentFlag.AlignHCenter)
        self.vBox.addWidget(self.templatePath)
        self.vBox.addWidget(self.excelEdit)
        self.vBox.addWidget(self.saveEdit)
        self.vBox.addWidget(self.table)
        self.vBox.addWidget(self.startButton)

        self.stateToolTip = StateToolTip('转换中...', '正在根据模板创建PPT文件，请稍后...', parent=self)
        self.stateToolTip.hide()

        self.replace_thread = PPtReplaceThread(self)
        self.replace_thread.started.connect(self.started_thread)
        self.replace_thread.error.connect(lambda msg: InfoBar.error('错误', msg, duration=5000, parent=self))
        self.replace_thread.finished.connect(self.finished_thread)

    def get_template_path(self):
        file = OpenFileDialog(self).getOpenFileName(filter='PPT文件(*.pptx;*.ppt)')[0]
        self.templatePath.setText(file)
        if file == '':
            return
        self.table.clear()
        ppt = PPtReplace(file)
        for v in ppt.get_variable():
            self.table.addItem([v, ''])
        self.table.addItem(['保存文件名称', ''])

    def get_save_dir(self):
        file = OpenFileDialog(self).getExistingDirectory()
        self.saveEdit.setText(file)

    def startButtonEvent(self):
        templatePath = self.templatePath.text()
        excelPath = self.excelEdit.text()
        savePath = self.saveEdit.text()
        if templatePath == '' or savePath == '' or excelPath == '':
            InfoBar.warning('提示', '请选择相关路径', duration=3000, parent=self)
            return
        if len(self.table.getColumnValues(0)) == 0:
            return
        data = dict(zip(self.table.getColumnValues(0), self.table.getColumnWidgetText(1)))
        self.replace_thread.set_value(templatePath, excelPath, savePath, data)
        self.replace_thread.start()

    def get_excel_path(self):
        file = OpenFileDialog(self).getOpenFileName(filter='Excel表格文件(*.xlsx;*.xls)')[0]
        self.excelEdit.setText(file)
        if file == '':
            return
        columns = read_excel(file).columns

        for index, col in enumerate(self.table.getColumnValues(0)):
            comboBox = ComboBox()
            comboBox.addItems(columns)
            comboBox.currentText()
            self.table.setCellWidget(index, 1, comboBox)

    def started_thread(self):
        self.stateToolTip.show()

    def finished_thread(self):
        self.stateToolTip.hide()
        InfoBar.success('成功', 'Word文件转换成功', parent=self)

    def returned_event(self):
        self.table.clear()
        self.templatePath.clear()
        self.excelEdit.clear()
        self.saveEdit.clear()
        super().returned_event()

    def on_helpButton_clicked(self):
        self.helpDialog = HelpDialog(self)
        self.helpDialog.show()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    win = PPtReplaceView()
    win.resize(600, 600)
    win.show()
    sys.exit(app.exec())
